//
//  HistoryLotteryViewController.m
//  BCW
//
//  Created by Mac on 16/3/29.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "HistoryLotteryViewController.h"
#import "UIBarButtonItem+CustomItem.h"
#import "HistoryTableView.h"
#import "BCWNavItem.h"
#import "PKView.h"
#import "HistoryModel.h"
#import "HistoryCell.h"
#import "LotteryCellModel.h"
#import "DateManager.h"
#import "LotteryStatusResultModel.h"
#import "LotteryTableView.h"

@interface HistoryLotteryViewController()
@property (nonatomic,strong) NSTimer            *adTimer;
@property (nonatomic, strong) UIView            *allView;
@property (nonatomic, strong) UIView            *headView;
@property (nonatomic, strong) UIView            *titleView;
@property (nonatomic, strong) HistoryTableView  *tableview;
@property (nonatomic, strong) UILabel           *noticL;

// 滚动时间
@property (nonatomic, assign) NSTimeInterval    timeInterval;
@property (nonatomic, strong) NSTimer           *timer;
@property (nonatomic, strong) PKView            *datePicker;
@property (nonatomic, strong) HBWNetDataManager *manager;
@property (nonatomic, strong) UILabel           *lotteryStatuL;
@property (nonatomic, strong) UILabel           *prompt;
@property (nonatomic, strong) UIScrollView           *advert;
//@property (nonatomic, strong) UILabel          *affichetext;

@end


@implementation HistoryLotteryViewController
{
    
    UIView *timeview ;
    UILabel *timetxt;
    UILabel  *affichetext;

}
- (HBWNetDataManager *)manager
{
    if (!_manager) {
        _manager = [HBWNetDataManager shareSessionManager ];
    }
    return _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [SVProgressHUD showWithStatus:@"加载中..."];
    // 导航条
    [self setupNavBar];
    // 广告
    [self setupAdvertisingView];
    [self setupTableview];
    [self setupRefresh];
    [self loadAdvertImg];
    // 添加观察者
    [DateMgr addObserver:self forKeyPath:@"bcwDate" options:NSKeyValueObservingOptionNew context:nil];
    // 通知中心 添加观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"NeedReloadData" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endTime) name:@"endTime" object:nil];
}


- (void)endTime{
    _lotteryStatuL.text = @"正在开奖";
}

- (void)refreshData{
    
    // 延迟30秒
    [self performSelector:@selector(loadData) withObject:nil afterDelay:31];
}

- (void)loadAdvertImg{
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    param[@"type"] = @"2";
    [NetMgr advertImgWithParam:param Success:^(id responeseObj) {
        NSArray *arr =responeseObj[@"data"];
        [self setAdvertViewWithData:arr];
    } failuer:^(NSError *error) {
        
    }];
    
    [NetMgr affichetextWithParam:(NSMutableDictionary *)param Success:^(id responeseObj) {
        affichetext.text = [NSString stringWithFormat:@"%@",responeseObj[@"data"]];
    } failuer:^(NSError *error) {
    }];
}






- (void)setAdvertViewWithData:(NSArray *)data{
    
    CGFloat x = 0;
    
    for (NSString *url in data) {
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, _advert.width, _advert.height)];
        [img sd_setImageWithURL:[NSURL URLWithString:url]];
        [_advert addSubview:img];
        
        x += _advert.width;
    }
    
    if (data.count >= 2) {
        [self advertTimerWithCount:data.count];
    }
    
}

- (void)advertTimerWithCount:(NSInteger)count{
    _adTimer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(changeAdOffset:) userInfo:@(count) repeats:YES];
}

- (void)changeAdOffset:(NSTimer *)sender{
    //    NSLog(@"%li", [sender.userInfo integerValue]);
    if (_advert.contentOffset.x / _advert.width == [sender.userInfo integerValue] - 1) {
        [_advert setContentOffset:CGPointMake(0, 0) animated:YES];
        return;
        
    }
    //    else{
    [_advert setContentOffset:CGPointMake(_advert.contentOffset.x + _advert.width, 0) animated:YES];
    //    }
    
    
    //    _homeview.advertContainer.contentOffset = CGPointMake(_homeview.advertContainer.contentOffset.x + _homeview.advertContainer.width, 0);
    
    
}



- (void)dealloc{
    [_adTimer invalidate];
    
    [self removeObserver:DateMgr forKeyPath:@"bcwDate"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupRefresh{
    [SVProgressHUD showWithStatus:@"加载中..."];

    _tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    // 自动改变透明度
    _tableview.mj_header.automaticallyChangeAlpha = YES;
    [_tableview.mj_header beginRefreshing];
}

- (void)loadData{
    // 结束上啦
    [_tableview.mj_footer endRefreshing];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc] init];
    [self.manager HistoryLotteryWithParams:param Success:^(id responeseObj) {
        
        NSMutableArray * arr = [HistoryModel mj_objectArrayWithKeyValuesArray:responeseObj];
        _tableview.historyArr = arr;
        _tableview.lotteryModel = _lotteryModel;
        [_tableview reloadData];
        [SVProgressHUD dismiss];
    } failuer:^(NSError *error) {
        
    }];
//    [self.manager homeLotterySuccess:^(id responeseObj) {
//        
//        
//    } failuer:^(NSError *error) {
//    }];
    
    // 结束上啦
    [_tableview.mj_header endRefreshing];

}

- (void)reloaddata{
    NSInteger phase = [[_lotteryModel.next_phase substringFromIndex:8] integerValue];
    _prompt.text = [NSString stringWithFormat:@"距离第%li期开奖剩余:", phase];
}

- (void)setupNavBar{
    self.navigationController.navigationBar.barTintColor = ThemeColor;
    
    // titleView
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];
    self.navigationItem.titleView = titleView;
    UILabel *prompt = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleView.width, 20)];
    prompt.font = SystemFont(12);
    NSInteger phase = [[_lotteryModel.next_phase substringFromIndex:8] integerValue];
    prompt.text = [NSString stringWithFormat:@"距离第%li期开奖剩余:", phase];
    [titleView addSubview:prompt];
    prompt.textColor = WhiteColor;
    prompt.textAlignment = 1;
    
    UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(0, prompt.bottom + 2, 80, 20)];
    status.backgroundColor = [UIColor whiteColor];
    
    //    status.text = @"正在开奖";
    if (DateMgr.bcwDate.m == 0 && DateMgr.bcwDate.s == 0) {
        status.text = @"正在开奖";
    }
    else{
        status.text = [NSString stringWithFormat:@"%.2li:%.2li", DateMgr.bcwDate.m, DateMgr.bcwDate.s];
    }
    
    [titleView addSubview:status];
    status.textColor = ThemeColor;
    status.font = BoldFont(20);
    status.textAlignment = 1;
    status.centerX = prompt.centerX;
    _lotteryStatuL = status;
    //    self.ststusL = status;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"return"
                                                                hightImage:@"return"
                                                                    target:self
                                                                    action:@selector(popVC)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"share-connection"
                                                                 hightImage:@"share-connection"
                                                                     target:self
                                                                     action:@selector(rightClick)];
}

#pragma mark ------------------------头部几个View-----------------------
- (void)setupAdvertisingView{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.view.width, 50)];
    
    [self.view addSubview:bgView];
    self.headView = bgView;
    
    _advert = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, bgView.width, 35)];
    //    advertising.image = [UIImage imageNamed:@"mai"];
    [bgView addSubview:_advert];
    
    // Notice
    UIView *noticeView = [[UIView alloc] initWithFrame:CGRectMake(0, _advert.bottom, _advert.width, 15)];
    noticeView.backgroundColor = WhiteColor;
    [bgView addSubview:noticeView];
    
    UIImageView *soundImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, noticeView.height)];
    soundImg.image = [UIImage imageNamed:@"radio"];
    soundImg.backgroundColor = WhiteColor;
    
    UILabel *noticText = [[UILabel alloc] initWithFrame:CGRectMake(soundImg.right + 5, 0, noticeView.width - soundImg.width, soundImg.height)];
    noticText.font = SystemFont(12);
    [noticText sizeToFit];
    self.noticL = noticText;
    affichetext.text = noticText.text;
    [noticeView addSubview:noticText];
    [noticeView addSubview:soundImg];
    
    [self beginTimer];

    //历史开奖View
    timeview = [[UIView alloc]initWithFrame:CGRectMake(0, noticeView.bottom, self.view.width, 30)];
    [bgView addSubview:timeview];
    UIView *lingview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    lingview.backgroundColor = [UIColor grayColor];
    [timeview addSubview:lingview];

    //日期
    timetxt = [[UILabel alloc]initWithFrame:CGRectMake(BCWScreenW/4, 1, 250, 30)];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strtime = [formatter stringFromDate:[NSDate date]];
    timetxt.text = strtime;
    timetxt.font = SystemFont(15);
    [timeview addSubview:timetxt];
    [self setupRefresh];
    
    UILabel *histoey_txt = [[UILabel alloc]init];
    histoey_txt.frame = CGRectMake(BCWScreenW/2+5, 1, 100, 30);
    histoey_txt.text =@"历史开奖";
    histoey_txt.font = SystemFont(15);
    [timeview addSubview:histoey_txt];
    
    UIButton *timerBtn = [[UIButton alloc]init];
    [timerBtn setImage:[UIImage imageNamed:@"Under_1"] forState:UIControlStateNormal];
    timerBtn.frame = CGRectMake(BCWScreenW - 65, -5, 60, 40);
    [timerBtn addTarget:self action:@selector(timerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [timeview addSubview:timerBtn];

}


//TODO:代理 
- (void)passValue:(NSString *)value{
    
    [_tableview.mj_header beginRefreshing];
    NSString *valueStr=[NSString stringWithFormat:@"%@",value];
    timetxt.text = valueStr;
}

- (void)setupTableview{
    HistoryTableView *historyTable = [[HistoryTableView alloc] initWithFrame:CGRectMake(0, _headView.bottom, self.view.width, self.view.height - _headView.bottom) style:UITableViewStyleGrouped];
    _tableview = historyTable;
    [self.view addSubview:historyTable];
}

- (void)popVC{
    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
}

- (void)rightClick
{
    NSLog(@"呵呵哒");
}

- (void)beginTimer{
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(beginAnima) userInfo:nil repeats:NO];
}

- (void)beginAnima{
    CGFloat moveW = _noticL.width;
    if (_noticL.x == _headView.width) {
        moveW += _headView.width - 15;
    }
    // 时间
    NSTimeInterval interval = moveW / 35.f;// 30为速度
    _timeInterval = interval;
    
    [UIView animateKeyframesWithDuration:interval
                                   delay:0
                                 options:UIViewKeyframeAnimationOptionBeginFromCurrentState
                              animations:^{
                                  _noticL.x -= moveW;
                              } completion:^(BOOL finished) {
                                  _noticL.x = _headView.width;
                                  
                                  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(beginAnima) userInfo:nil repeats:NO];
                              }];
}


-(void)timerBtnClick
{
    [self.datePicker removeFromSuperview];

    PKView *datePicker=[[PKView alloc]init];
    datePicker.frame = CGRectMake(0, 0, BCWScreenW, BCWScreenH);
    datePicker.delegate=self;
    [self.view addSubview:datePicker];
    self.datePicker=datePicker;

    CATransition *animation = [CATransition animation];
    animation.duration = 0.6f;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.type = kCATransitionMoveIn;
    animation.subtype = kCATransitionFromTop;
    [self.datePicker.layer addAnimation:animation forKey:@"animation"];
}


/**
 * 状态栏为白色
 */
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.datePicker removeFromSuperview];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    _lotteryStatuL.text = [NSString stringWithFormat:@"%.2li:%.2li", DateMgr.bcwDate.m, DateMgr.bcwDate.s];
}



@end
